// ****************************************************************************
// Configs
// ****************************************************************************

// PUSH server configs
var PUSH_PORT       = 8765,
    PUSH_URL_PREFIX = '/push';

// Redis configs
var REDIS_HOST = '120.26.100.85',
    REDIS_PORT = 9630,
    REDIS_PASS = '19872hayuigubQY9gaYWoetgytYTQPGLGQE_+weitht92hdgGHOGQ';

// Interested redis channels
// Contains channelNames, separated by spaces.
var REDIS_CHANNELS = 'msgchannel ctlchannel';


// Log method
function log(msg) {
    console.log(msg);
}


// ****************************************************************************
// Init push server
// ****************************************************************************
var pushServer = require('./push.js');

pushServer.init({
    port   : PUSH_PORT,
    prefix : PUSH_URL_PREFIX

// On user enter, update redis set
}, function(userId) {

    var info    = userId.split('+'),
        id      = +info[0],
        isAdmin = +info[1];

    if (!isAdmin) {
        // DEBUG
        console.log('User ' + id + ' enter.');
        console.log(cmdRedis.sadd('session:accountid:group:' + (id % 50), id));
        cmdRedis.incr('session:accountid:count');
    }

// On user leave, update redis set
}, function(userId) {

    var info    = userId.split('+'),
        id      = +info[0],
        isAdmin = +info[1];

    if (!isAdmin) {
        // DEBUG
        console.log('User ' + id + ' leave.');
        console.log(cmdRedis.srem('session:accountid:group:' + (id % 50), id));
        cmdRedis.decr('session:accountid:count');
    }
});

// ****************************************************************************
// Init redis client
// ****************************************************************************
var subRedis = require('redis').createClient(REDIS_PORT, REDIS_HOST, {auth_pass: REDIS_PASS}),
    cmdRedis = require('redis').createClient(REDIS_PORT, REDIS_HOST, {auth_pass: REDIS_PASS});
// DEBUG
// var subRedis = require('redis').createClient(6379, '127.0.0.1'),
//     cmdRedis = require('redis').createClient(6379, '127.0.0.1');

subRedis.on('connect', function() {

    console.log('Connected to redis server ' + REDIS_HOST + ':' + REDIS_PORT);

    var channels = REDIS_CHANNELS.split(/ +/);

    for (var i = channels.length; i--;) {
        subRedis.subscribe(channels[i]);
    }

    subRedis.on('message', function(channel, message) {

        // Socket channels: 1, 2, 3
        //
        // 1: user loggedin
        // 2: admin
        // 3: user no-loggedin

        // DEBUG
        console.log('redis channel: ' + channel + '\tredis message: ' + message);

        // Handle message
        if (channel === 'msgchannel') {

            // DEBUG
            // console.log('msgchannel ' + message);

            var info       = message.split('+++'),
                isAdmin    = (info[0] === '1' ? '1' : '0'),
                loginState = info[1],
                userId     = (info[2] === '-1' ? null : info[2]),
                message    = info[3];

            // Push to a specified user
            if (userId !== null) {
                pushServer.pushUserId(message, userId + '+' + isAdmin);
                // DEBUG
                console.log('Push to user ' + userId + '+' + isAdmin);

            // Push to all admins
            } else if (isAdmin === '1') {
                pushServer.pushChannel(message, '2');
                // DEBUG
                console.log('Push to all admins');

            // Push to all users
            } else if (loginState === '3') {
                pushServer.pushChannel(message, '1');
                pushServer.pushChannel(message, '3');
                // DEBUG
                console.log('Push to all users');

            // Push to login / nologin users
            } else {
                pushServer.pushChannel(message, loginState === '1' ? '1' : '3');
                // DEBUG
                console.log('Push to users ' + (loginState === '1' ? 'loggedin' : 'no-loggedin'));
            }

        // Handel commands
        } else if (channel === 'ctlchannel') {

            // DEBUG
            console.log('ctlchannel ' + message);

            var info    = message.split('+++'),
                sign    = info[0],
                userId  = info[1],
                isAdmin = info[2],
                sockUserId = (userId === '-1' || userId === 'undefined') ?
                        null : (userId + '+' + isAdmin);
                channel = isAdmin === '1' ? '2' : (sockUserId === null ? '3' : '1');

            pushServer.register(channel, sockUserId, sign);

            // DEBUG
            console.log('Register: channel ' + channel + ' sockUserId ' +
                    sockUserId);
        }
    });
});


// // ****************************************************************************
// // Init HTTP interface for testing
// //
// // THIS MUST BE DISABLED BEFORE PUBLISHMENG !!!!!!!!
// // ****************************************************************************

// // DEBUG
// // var redisTest = require('redis').createClient(REDIS_PORT, REDIS_HOST, {auth_pass: REDIS_PASS});

// var app = require('express')();

// // Get param: { data: data, callback: callback }
// app.get('/redis', function(req, resp) {

//     var respData = JSON.stringify({ success: true }),
//         channel  = req.query.channel,
//         data     = req.query.data;

//     // Do push data
//     channel && data && cmdRedis.publish(channel, data);

//     // Handle jsonp
//     resp.send(req.query.callback ? req.query.callback + '(' + respData + ');' :
//             respData);
// });

// app.listen(12345, function() {
//     console.log('HTTP server started, listening on port ' + 12345);
// });
